﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lottery.api.Data;
using lottery.api.Models;
using lottery.api.Services;
using lottery.entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace lottery.api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class WechartController : ControllerBase
    {
        private readonly IWechatService _wechat;
        private readonly LotteryContext _context;

        public WechartController(IWechatService wechat, LotteryContext context)
        {
            this._context = context;
            this._wechat = wechat;
        }

        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/wechat
        [HttpPost("login")]
        public async Task<IActionResult> Post([FromBody] string code)
        {
            SessionBody sessionBody = await _wechat.GetSession(code);
            var user = _context.Users.SingleOrDefault(d => d.WechartId == sessionBody.openid);
            if (user == null)
            {
                user = new User()
                {
                    CreateDate = DateTime.Now,
                    Status = Status.Normal,
                    WechartId = sessionBody.openid,
                    WechartSession = sessionBody.session_key
                };
                _context.Add(user);
            }
            else
            {
                user.WechartSession = sessionBody.session_key;
            }
            await _context.SaveChangesAsync();

            HttpContext.Session.SetString("wechat_session_key", user.WechartSession);

            return Ok();
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
